package cn.goktech.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.google.gson.Gson;

import cn.goktech.entity.Comment;
import cn.goktech.service.ICommentService;
import cn.goktech.service.impl.CommentServiceImpl;

@WebServlet("/CommentServlet")
public class CommentServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		request.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");
		
		String task=request.getParameter("task");
		
		PrintWriter out = response.getWriter();
		HttpSession session = request.getSession();
		
		ICommentService commentService = new CommentServiceImpl();
		
		if("querycommentList".equals(task)){
			int articleId = Integer.parseInt(request.getParameter("articleId"));
			List<Comment> commentList = commentService.commentList(articleId);
			if(commentList!=null){
				Gson gson = new Gson();
				String string = gson.toJson(commentList);
				out.print(string);
			}
		}else if("addcomment".equals(task)){
			int articleId = Integer.parseInt(request.getParameter("articleId"));
			String commentUser = request.getParameter("commentUser");
			String commentContent = request.getParameter("comment");
			String commentimg = request.getParameter("img");
			Date date = new Date();//获得系统时间.
			
			Comment comment = new Comment();
			comment.setArticleId(articleId);
			comment.setComment(commentContent);
			comment.setCommentUser(commentUser);
			comment.setImg(commentimg);
			comment.setTime(date);
			
			int insertComment = commentService.insertComment(comment);
			if(insertComment>0){
				out.write("true");
			} else {
				out.write("false");
			}
			
		}else if("delete".equals(task)){
			int id = Integer.parseInt(request.getParameter("id"));
			int deleteComment = commentService.deleteComment(id);
			if(deleteComment>0){
				out.write("true");
			} else {
				out.write("false");
			}
			
		}
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
